/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xtd.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lu Yuanbin
 */
public class DateTimeUtil {

    public static DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");

    public static Date getDateBefore(Date date, int i) {
        Calendar c = new GregorianCalendar();
        c.setTime(date);
        c.add(Calendar.DATE, -i);
        return getDateStart(c.getTime());
    }

    public static Date getDateStart(Date date) {
        try {
            return formatter.parse(formatter.format(date));
        } catch (ParseException ex) {
            Logger.getLogger(DateTimeUtil.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public static Date getDateEnd(Date date) {
        Calendar c = new GregorianCalendar();
        try {
            Date parsedDate = formatter.parse(formatter.format(c.getTime()));
            c.setTime(parsedDate);
            c.add(Calendar.DATE, 1);
            c.add(Calendar.SECOND, -1);
            return c.getTime();
        } catch (ParseException ex) {
            Logger.getLogger(DateTimeUtil.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public static Date getWeekStart() {
        Calendar c = new GregorianCalendar();

        return getDateBefore(c.getTime(), c.get(Calendar.DAY_OF_WEEK) - 1);
    }

    public static Date getMonthStart() {
        Calendar c = new GregorianCalendar();

        c.set(Calendar.DAY_OF_MONTH, 1);

        return getDateStart(c.getTime());
    }

    public static Date getTodayStart() {
       return getDateStart(new Date());
    }
    public static Date getTodayEnd() {
        return getDateEnd(new Date());
    }
}
